import React from 'react';
import moment from 'moment';
import cn from 'classnames';

import { Button } from 'antd';
import { useDict, useTalentDetail, useTalentTable } from './hooks';
import ApplicationTable from './ApplicationTable';
import styles from './index.less';

// eslint-disable-next-line react/no-danger
const empty = <span dangerouslySetInnerHTML={{ __html: '&nbsp' }} />; // 要不然会换行？

const formatDate = value => value && moment(value).format('YYYY-MM');
const formatDateRange = (start, end) => {
    if (start && end) {
        return [formatDate(start), formatDate(end)].join('~');
    }
    return '';
};
const formatPhone = (area, phone) => {
    const result = [];
    if (area) result.push(`+${area}`);
    if (phone) result.push(phone);
    return result.join(' ');
};

const Print = ({ location }) => {
    const {
        query: { code }
    } = location;

    const [, detail] = useTalentDetail({ code });
    const [, tableData] = useTalentTable({ code });

    const [, dictList] = useDict({
        codes: [
            'agreeType',
            'sexType',
            'healthyState',
            'emergencyRelationship',
            'household',
            'liveTogether',
            'backCheckAccepted',
            'SingaporeRecruitWay',
            'academicYear',
            'industryType',
            'ChinaRecruitWay'
        ]
    });

    // 获取字典item
    const getDictItem = (dictValue, field, list = dictList) =>
        list.find(item => String(item.dictValue) === String(dictValue) && item.code === field) || {};

    // 获取字典dictName
    const getDictValue = (dictValue, field, list = dictList) => {
        const dictItem = getDictItem(dictValue, field, list);
        return dictItem.dictName || '';
    };

    // 户籍类型的查询，还是那个味儿，一级字典->parentId->二级字典，绕得很
    const firstHouseHoldType = getDictItem(detail.firstHouseholdType, 'household');
    const [, houseHoldList] = useDict({ parentId: firstHouseHoldType.id });
    const houseHoldTypeResult = `${firstHouseHoldType.dictName || ''} ${getDictValue(
        detail.secondHouseholdType,
        'household2',
        houseHoldList
    ) || ''}`;

    const fieldsMap1 = [
        {
            label: '姓名',
            key: 'talentName'
        },
        {
            label: '性别',
            key: 'talentSex',
            render: value => getDictValue(value, 'sexType')
        },
        {
            label: '手机号码',
            key: 'talentPhone',
            render: (value, record) => formatPhone(record.talentAreaCode, value)
        },
        {
            label: '个人邮箱',
            key: 'talentEmail'
        },
        {
            label: '证件号码',
            key: 'talentIdCard'
        },
        {
            label: '出生日期',
            key: 'talentBirth'
        },
        {
            label: '籍贯/国籍',
            key: 'talentNationalArea'
        },
        {
            label: '户籍类型',
            key: 'firstHouseholdType',
            isHide: (detail.talentNationalArea || '').split(',')[0] !== '中国',
            render: () => houseHoldTypeResult
        },
        {
            label: '居住地址',
            key: 'detailAddress',
            render: () => `${detail.address || ''}${detail.detailAddress || ''}`
        },
        {
            label: '最高学历',
            key: 'talentDegree',
            render: value => getDictValue(value, 'agreeType')
        },
        {
            label: '学校名称',
            key: 'talentGraduateSchool'
        },
        {
            label: '专业',
            key: 'talentProfessional'
        },
        {
            label: '健康状态',
            key: 'healthyState',
            render: (value, record) => {
                if (value === 'other') {
                    return `${getDictValue(value, 'healthyState')} ${record.healthyStateDesc}`;
                }
                return getDictValue(value, 'healthyState');
            }
        },
        {
            label: '身高体重',
            key: 'heightWeight'
        }
    ];

    const fieldsMap2 = [
        {
            label: '姓名',
            key: 'emergencyContact'
        },
        {
            label: '与本人关系',
            key: 'emergencyRelationship',
            render: value => getDictValue(value, 'emergencyRelationship')
        },
        {
            label: '手机号码',
            key: 'emergencyTelephone',
            render: (value, record) => formatPhone(record.emergencyAreaCode, value)
        }
    ];

    const fieldsMap3 = [
        {
            label: '同岗经验/年',
            key: 'talentExperience'
        },
        {
            label: '最快到岗时间',
            key: 'comePositionDate'
        },
        {
            label: '月薪要求',
            key: 'monthSalaryDemand'
        },
        {
            label: '其它福利要求',
            key: 'otherBenefitDemand'
        },
        {
            label: '应聘渠道',
            key: 'notesSource',
            render: (value, record) => {
                const recruitWay = getDictValue(value, 'ChinaRecruitWay') || getDictValue(value, 'SingaporeRecruitWay');
                if (value === 'other' || value === 'internal_recommendation' || value === 'forum') {
                    return `${recruitWay} ${record.notesSourceDetail}`;
                }
                return recruitWay;
            }
        },
        {
            label: '确认录用后，是否接受背调',
            key: 'backCheckAccept',
            render: value => {
                // 这接口...
                if (value === '') return '';
                const map = { 0: '否', 1: '是' };
                return map[Number(value)];
            }
        }
    ];

    const noWorkExperience = detail.recruitTalentWorks && !detail.recruitTalentWorks.length;
    const getWorkFields = () => {
        if (noWorkExperience) {
            return [
                {
                    label: '工作经验',
                    key: 'workExp',
                    render: () => '无'
                }
            ];
        }
        return [
            {
                label: '起止时间',
                key: 'startTime',
                render: (value, record) => formatDateRange(record.startTime, record.endTime)
            },
            {
                label: '工作单位',
                key: 'organize'
            },
            {
                label: '行业/主营业务',
                key: 'industry',
                render: value => getDictValue(value, 'industryType')
            },
            {
                label: '职位',
                key: 'post'
            },
            {
                label: '离职原因',
                key: 'reason'
            },
            {
                label: '直接上级',
                key: 'approveName'
            },
            {
                label: '手机号码',
                key: 'approvePhone',
                render: (value, record) => formatPhone(record.areaCode, value)
            }
        ];
    };
    const workSourceOption = () => {
        if (noWorkExperience) return {};
        return {
            dataSource: detail.recruitTalentWorks
        };
    };
    const fieldsMap5 = [
        {
            label: '起止时间',
            key: 'startTime',
            render: (value, record) => formatDateRange(record.startTime, record.endTime)
        },
        {
            label: '专业',
            key: 'major'
        },
        {
            label: '学校名称',
            key: 'graduateSchool'
        },
        {
            label: '毕业证书',
            key: 'degree'
        },
        {
            label: '学制',
            key: 'academicYear',
            render: value => getDictValue(value, 'academicYear')
        }
    ];

    const fieldsMap6 = [
        {
            label: '起止时间',
            key: 'startTime',
            render: (value, record) => formatDateRange(record.startTime, record.endTime)
        },
        {
            label: '培训主题/内容',
            key: 'trainContent'
        },
        {
            label: '培训机构',
            key: 'trainOrganize'
        },
        {
            label: '证书',
            key: 'certificate'
        }
    ];

    const fieldsMap7 = [
        {
            label: '获奖时间',
            key: 'awardTime',
            render: value => formatDate(value)
        },
        {
            label: '奖项名称',
            key: 'awardName'
        },
        {
            label: '颁发机构',
            key: 'organize'
        }
    ];

    const fieldsMap9 = [
        {
            label: '应聘职位',
            key: 'recruitPost'
        },
        {
            label: '公司',
            key: 'companyName'
        },
        {
            label: '添加候选时间',
            key: 'createTime'
        },
        {
            label: '阶段',
            key: 'candidateStageValue'
        },
        {
            label: '状态',
            key: 'candidateStateValue'
        },
        {
            label: '招聘负责',
            key: 'candidateLeaderName'
        }
    ];

    const renderItem = (item, record) => {
        const { label, key, render } = item;
        const value = render ? render(record[key], record, key) : record[key] || empty;
        return (
            <>
                <em>{label}: </em>
                {value}
            </>
        );
    };

    const renderTable = (rows, record = detail) => {
        const filterRows = rows.filter(item => !item.isHide);
        return filterRows.map((item, index) => {
            if (index % 2 === 0) {
                return (
                    <tr key={`${record.id}${item.key}`}>
                        <td>{filterRows[index] ? renderItem(filterRows[index], record) : null}</td>
                        <td>{filterRows[index + 1] ? renderItem(filterRows[index + 1], record) : null}</td>
                    </tr>
                );
            }
            return null;
        });
    };
    const renderContent = (cfg = []) => {
        const getTable = list => {
            if (list.dataSource) {
                return list.dataSource.map(item => (
                    <table className={cn(styles.formTable, styles.subFormTable)} key={item.id}>
                        <tbody>{renderTable(list.fields, item)}</tbody>
                    </table>
                ));
            }
            return (
                <table className={styles.formTable}>
                    <tbody>{renderTable(list.fields)}</tbody>
                </table>
            );
        };

        return cfg.map(list => {
            const content =
                list.dataSource && !list.dataSource.length ? (
                    <div style={{ textIndent: 20 }}>暂无信息</div>
                ) : (
                    getTable(list)
                );
            return (
                <div className={styles.section} key={list.title}>
                    <h3 className={styles.mainTitle}>{list.title}</h3>
                    {content}
                </div>
            );
        });
    };

    return (
        <div className={styles.wrap}>
            <div>
                <Button className={styles.btn} onClick={() => window.print()}>
                    打印
                </Button>
            </div>
            {renderContent([
                {
                    title: '个人信息',
                    fields: fieldsMap1
                },
                {
                    title: '紧急联系人',
                    fields: fieldsMap2
                },
                {
                    title: '应聘信息',
                    fields: fieldsMap3
                },
                {
                    title: '工作经历',
                    fields: getWorkFields(),
                    ...workSourceOption()
                },
                {
                    title: '教育经历',
                    fields: fieldsMap5,
                    dataSource: detail.recruitTalentEdus
                },
                {
                    title: '培训经历',
                    fields: fieldsMap6,
                    dataSource: detail.recruitTalentTrains
                },
                {
                    title: '获奖记录',
                    fields: fieldsMap7,
                    dataSource: detail.recruitTalentAwards
                }
            ])}
            <div className={styles.section}>
                <h3 className={styles.mainTitle}>应聘信息</h3>
                <div>
                    <ApplicationTable columns={fieldsMap9} dataSource={tableData} />
                </div>
            </div>
        </div>
    );
};

export default Print;
